package router

import (
	"strings"

	"apiGateWay/internal/config"
	"apiGateWay/internal/handler"
	"apiGateWay/internal/middleware/auth"
	"apiGateWay/internal/middleware/cors"
	"apiGateWay/internal/middleware/rate_limit"
	"apiGateWay/internal/middleware/security"
	"apiGateWay/internal/proxy"
	"apiGateWay/pkg/logger"

	"github.com/gin-gonic/gin"
)

// Router 路由器
type Router struct {
	Engine *gin.Engine
	cfg    *config.Config
}

// NewRouter 创建新的路由器
func NewRouter(cfg *config.Config) *Router {
	r := gin.New()

	// 基础中间件
	r.Use(gin.Recovery())
	r.Use(logger.GinLogger())
	r.Use(security.SecurityHeaders(cfg))

	// CORS 中间件
	if cfg.CORS.Enabled {
		r.Use(cors.CORSMiddleware(cfg))
	}

	router := &Router{
		Engine: r,
		cfg:    cfg,
	}

	// 注册路由
	router.registerRoutes()

	return router
}

// registerRoutes 注册所有路由
func (r *Router) registerRoutes() {
	// 健康检查
	r.Engine.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"status":  "ok",
			"service": "api-gateway",
		})
	})

	// 认证相关路由
	authGroup := r.Engine.Group("/auth")
	{
		authGroup.POST("/login", auth.LoginHandler(r.cfg))
		authGroup.POST("/refresh", auth.RefreshTokenHandler(r.cfg))
		authGroup.GET("/oauth2/:provider", auth.OAuth2LoginHandler(r.cfg))
		authGroup.GET("/oauth2/callback/:provider", auth.OAuth2CallbackHandler(r.cfg))
	}

	// 管理接口路由组（需要认证）
	adminGroup := r.Engine.Group("/api/admin")
	adminGroup.Use(auth.JWTAuthMiddleware(r.cfg))
	{
		adminHandler := handler.NewAdminHandlerV2(r.cfg)
		// 路由管理
		adminGroup.GET("/routes", adminHandler.GetRoutes)
		adminGroup.POST("/routes", adminHandler.CreateRoute)
		adminGroup.PUT("/routes/:id", adminHandler.UpdateRoute)
		adminGroup.DELETE("/routes/:id", adminHandler.DeleteRoute)
		
		// 日志管理
		adminGroup.GET("/logs", adminHandler.GetLogs)
		
		// 统计信息
		adminGroup.GET("/statistics", adminHandler.GetStatistics)
		
		// 配置管理
		adminGroup.GET("/config", adminHandler.GetSystemConfig)
		adminGroup.PUT("/config", adminHandler.UpdateSystemConfig)
		adminGroup.POST("/config/reload", adminHandler.ReloadConfig)
		adminGroup.GET("/config/auth", adminHandler.GetAuthConfig)
		adminGroup.PUT("/config/auth", adminHandler.UpdateAuthConfig)
		adminGroup.GET("/config/rate-limit", adminHandler.GetRateLimitConfig)
		adminGroup.PUT("/config/rate-limit", adminHandler.UpdateRateLimitConfig)
	}

	// API 路由组
	apiGroup := r.Engine.Group("")
	{
		// 加载路由（优先从数据库，否则从配置文件）
		routes := LoadRoutes(r.cfg)
		// 为每个路由创建代理
		for _, route := range routes {
			r.registerRoute(route, apiGroup)
		}
	}
}

// registerRoute 注册单个路由
func (r *Router) registerRoute(route config.RouteConfig, group *gin.RouterGroup) {
	// 创建路由处理器
	handler := proxy.NewProxyHandler(route, r.cfg)

	// 应用限流中间件
	if r.cfg.RateLimit.Enabled && route.RateLimit.Enabled {
		group.Use(rate_limit.RateLimitMiddleware(route.RateLimit, r.cfg))
	}

	// 应用认证中间件
	if route.AuthRequired {
		group.Use(auth.JWTAuthMiddleware(r.cfg))
	}

	// 注册路由
	// 处理路径中的 ** 通配符，转换为 Gin 支持的路径参数
	ginPath := route.Path
	if strings.Contains(ginPath, "**") {
		// 将 ** 替换为 Gin 支持的通配符格式
		// 例如: /api/v1/users/** -> /api/v1/users/*
		ginPath = strings.ReplaceAll(ginPath, "**", "*")
		// 或者使用参数: /api/v1/users/** -> /api/v1/users/*path
		// 但 Gin 的 * 不支持多级匹配，我们需要用不同的方式
		// 改为使用 :path* 或者直接去掉通配符，在处理器中处理
		ginPath = strings.TrimSuffix(ginPath, "*")
		if !strings.HasSuffix(ginPath, "/") {
			ginPath += "/"
		}
		ginPath += "*filepath"
	}
	
	for _, method := range route.Methods {
		group.Handle(method, ginPath, handler.Handle)
	}

	logger.Infof("注册路由: %s %s -> %s", route.Methods, route.Path, route.Target)
}

